<template>
	<view class="page">
		<!-- 右上角：跳过（弹窗确认后无课程ID进入跑步页） -->
		<view class="skip" @tap="onSkip">
			<text class="skip-text">跳过</text>
		</view>

		<!-- 顶部统计（与跑步记录页风格一致） -->
		<view class="stats">
			<view class="stats-row">
				<view class="stats-col">
					<view class="num">{{ totalCourses }}</view>
					<view class="label">可选课程</view>
				</view>
				<view class="stats-col center">
					<view class="num big">{{ finishedCount }}</view>
					<view class="label">已完成</view>
				</view>
				<view class="stats-col">
					<view class="num">{{ doingCount }}</view>
					<view class="label">进行中</view>
				</view>
			</view>
		</view>

		<!-- 内容区（普通容器，不使用 scroll-view） -->
		<view class="content">
			<view class="card-list">
				<!-- 每张卡外包裹一层用于角标定位 -->
				<view class="card-wrap" v-for="c in courses" :key="c?.id || c?.name">
					<!-- 角标：固定在卡片右上角 -->
					<view class="corner-tag" :class="tagClass(c)">{{ tagText(c) }}</view>

					<wd-card class="course-card" @tap="onSelect(c)">
						<!-- 标题：目标步数 -->
						<template #title>
							<view class="card-title">
								<text class="title">{{ fmt(c.targetSteps) }}</text>
								<text class="unit">步</text>
							</view>
						</template>

						<!-- 主体 -->
						<template #default>
							<view class="card-body">
								<view class="row">
									<view class="col">
										<text class="label">达标步数：</text>
										<text class="val">{{ fmt(c.targetSteps) }}</text><text class="u">步</text>
									</view>
									<view class="col">
										<text class="label">当前进度：</text>
										<text class="val">{{ fmt(c.completedSteps) }}</text><text class="u">步</text>
									</view>
								</view>

								<view class="row">
									<view class="col">
										<text class="label">截止日期：</text>
										<text class="val">{{ deadline(c) }}</text>
									</view>

									<!-- 防止冒泡：用 @tap.stop 包住按钮 -->
									<view @tap.stop>
										<wd-button type="success" size="small" round @click="onSelect(c)">确认</wd-button>
									</view>
								</view>

								<!-- 进度条（条内隐藏文字） -->
								<view class="progress-wrap">
									<wd-progress class="pure-progress" :percentage="percent(c)" :show-text="false"
										:stroke-width="8" />
								</view>
							</view>
						</template>
					</wd-card>
				</view>

				<wd-divider v-if="totalCourses === 0">暂无课程</wd-divider>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		computed,
		ref
	} from 'vue'
	import {
		onShow
	} from '@dcloudio/uni-app'
	import {
		useAppStore
	} from '@/stores/app'

	const store = useAppStore()

	/* 进入页面，若本地暂无课程则拉取一次 */
	onShow(() => {
		if (!Array.isArray(store.courses) || store.courses.length === 0) {
			store.fetchCourses && store.fetchCourses()
		}
	})

	/* 永远返回数组，避免 undefined.length 报错 */
	const courses = computed(() => (Array.isArray(store.courses) ? store.courses : []))

	/* 顶部统计 */
	const totalCourses = computed(() => courses.value.length)
	const finishedCount = computed(() => courses.value.filter(isFinished).length)
	const doingCount = computed(() => courses.value.filter(c => !isFinished(c) && !isExpired(c)).length)

	/* 工具函数 */
	function fmt(n) {
		return (Number(n) || 0).toLocaleString('zh-CN')
	}

	function deadline(c) {
		return c?.deadline ? String(c.deadline).replace(/-/g, '.') : '-'
	}

	function percent(c) {
		const t = Number(c?.targetSteps || 0) || 1
		const cur = Number(c?.completedSteps || 0)
		return Math.min(100, Math.round((cur / t) * 100))
	}

	function isFinished(c) {
		const t = Number(c?.targetSteps || 0) || 1
		const cur = Number(c?.completedSteps || 0)
		return cur >= t
	}

	function isExpired(c) {
		if (!c?.deadline) return false
		const today = new Date();
		today.setHours(0, 0, 0, 0)
		const d = new Date(String(c.deadline).replace(/-/g, '/'));
		d.setHours(0, 0, 0, 0)
		return d.getTime() < today.getTime()
	}

	function tagText(c) {
		if (isFinished(c)) return '已完成'
		if (isExpired(c)) return '已截止'
		return '进行中'
	}

	function tagClass(c) {
		if (isFinished(c)) return 'done'
		if (isExpired(c)) return 'expired'
		return 'doing'
	}

	/* 重入锁：避免极快连续触发 */
	const selecting = ref(false)

	/* 交互 */
	function onSelect(c) {
		if (selecting.value) return
		selecting.value = true

		const t = tagText(c)
		const base = `《${c.name || '课程'}》
目标：${fmt(c.targetSteps)} 步
当前：${fmt(c.completedSteps)} 步`
		let content = base + '\n\n是否开始跑步并计入该课程？'
		if (t === '已完成') content = base + '\n\n该课程已完成，继续计入也会保留进度。是否继续？'
		else if (t === '已截止') content = base + '\n\n该课程已过截止日期，继续可能不计成绩。是否继续？'

		uni.showModal({
			title: '选择课程',
			content,
			confirmText: '是',
			cancelText: '否',
			success: ({
				confirm
			}) => {
				if (!confirm) return
				const id = c?.id
				if (!id) return uni.showToast({
					title: '缺少课程ID',
					icon: 'none'
				})
				uni.navigateTo({
					url: `/pages/run/running?courseId=${encodeURIComponent(String(id))}`
				})
			},
			complete: () => {
				selecting.value = false
			}
		})
	}

	/* 跳过：提示后无 ID 进入跑步页（可带来源参数） */
	function onSkip() {
		uni.showModal({
			title: '未选择课程',
			content: '确定直接开始跑步吗？本次进度不会计入任何课程。',
			confirmText: '开始',
			cancelText: '返回',
			success: ({
				confirm
			}) => {
				if (!confirm) return
				uni.navigateTo({
					url: '/pages/run/running?from=skip'
				})
			}
		})
	}
</script>

<style scoped>
	/* 背景同记录页 */
	.page {
		min-height: 100vh;
		background: linear-gradient(to bottom, #c4ffd5 0%, #f5f5f5 35%, #f5f5f5 100%);
	}

	/* 右上角跳过：磨砂胶囊 */
	.skip {
		position: fixed;
		top: 20rpx;
		right: 24rpx;
		z-index: 99;
		padding: 10rpx 20rpx;
		border-radius: 999rpx;
		background: rgba(255, 255, 255, .72);
		backdrop-filter: saturate(140%) blur(6rpx);
		border: 2rpx solid rgba(0, 0, 0, .06);
		box-shadow: 0 8rpx 18rpx rgba(0, 0, 0, .08);
	}

	.skip-text {
		font-size: 24rpx;
		color: #2b2b2b;
	}

	/* 顶部统计 */
	.stats {
		padding: 60rpx 30rpx 12rpx;
	}

	.stats-row {
		display: flex;
		justify-content: space-between;
		align-items: flex-start;
	}

	.stats-col {
		flex: 1;
		text-align: center;
	}

	.stats-col.center {
		flex: 1.5;
	}

	.num {
		font-size: 36rpx;
		font-weight: 600;
		color: #000;
		line-height: 1.2;
	}

	.num.big {
		font-size: 56rpx;
		font-weight: 700;
	}

	.label {
		margin-top: 10rpx;
		font-size: 24rpx;
		color: #333;
	}

	/* 内容区 */
	.content {
		padding: 16rpx 24rpx 60rpx;
	}

	.card-list {
		display: block;
	}

	/* 包裹容器：用于角标定位 */
	.card-wrap {
		position: relative;
		margin: 20rpx 6rpx;
	}

	/* 卡片本体 */
	.course-card {
		border-radius: 24rpx;
		overflow: hidden;
		box-shadow: 0 10rpx 24rpx rgba(0, 0, 0, .06);
	}

	:deep(.wd-card__header) {
		padding: 22rpx 24rpx;
	}

	:deep(.wd-card__body) {
		padding: 4rpx 24rpx 18rpx;
	}

	.card-title .title {
		font-size: 30rpx;
		font-weight: 700;
		color: #303030;
	}

	.card-title .unit {
		margin-left: 8rpx;
		font-size: 22rpx;
		color: #666;
	}

	.card-body {
		margin-top: 4rpx;
	}

	.row {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 14rpx 0;
		gap: 12rpx;
	}

	.col {
		display: flex;
		align-items: baseline;
		gap: 8rpx;
	}

	.label {
		color: #666;
		font-size: 26rpx;
	}

	.val {
		color: #222;
		font-size: 28rpx;
		letter-spacing: 1rpx;
	}

	.u {
		color: #444;
		font-size: 24rpx;
	}

	/* 角标定位到卡片右上角 */
	.corner-tag {
		position: absolute;
		top: 18rpx;
		right: 22rpx;
		z-index: 2;
		padding: 8rpx 18rpx;
		font-size: 22rpx;
		line-height: 1;
		border-radius: 999rpx;
		transform: rotate(-10deg);
		background: #fff;
		border: 2rpx solid #2e7d32;
		color: #2e7d32;
		box-shadow: 0 6rpx 14rpx rgba(0, 0, 0, .06);
	}

	.corner-tag.doing {
		border-color: #ff8a00;
		color: #ff8a00;
		background: #fffaf2;
	}

	.corner-tag.done {
		border-color: #2e7d32;
		color: #2e7d32;
		background: #f6fff8;
	}

	.corner-tag.expired {
		border-color: #e53935;
		color: #e53935;
		background: #fff5f5;
	}

	/* 进度条：隐藏组件自带文本 */
	.progress-wrap {
		margin-top: 6rpx;
		display: flex;
		align-items: center;
		gap: 16rpx;
	}

	.pure-progress :deep(.wd-progress__pivot),
	.pure-progress :deep(.wd-progress__text),
	.pure-progress :deep(.wd-progress__portion-text) {
		display: none !important;
	}
</style>